import { app, BrowserWindow, shell, ipcMain, Menu } from 'electron'
import { release } from 'node:os'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import http from 'http'
import fs from 'fs'
import path from 'path'
import formidable, { errors as formidableErrors } from 'formidable';
import axios from 'axios'
import os from "os"
import { doOCR } from './libs/ocrsdk'

import { test as testController } from './controller/test'
import { getMobileOcrResult } from './controller/getMobileOcrResult'
import { getMobileCameraImage } from './controller/getMobileCameraImage'


const port = 499;


const server = http.createServer(async (req, res) => {
  try {

    const pathName = new URL(`http://xx${req.url}`).pathname;

    res.writeHead(200, { 'Content-Type': 'application/json' });

    if (pathName == "/test") {
      return testController(req, res)
    }
    if (pathName == "/getMobileOcrResult") {
      return getMobileOcrResult(req, res, win)
    }
    if (pathName == "/getMobileCameraImage") {
      return getMobileCameraImage(req, res)
    }

    res.end(JSON.stringify({ code: 404 }));

  } catch (error) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    console.log("http.createServer error=> ", error);
  }
});

app.whenReady().then(() => {
  server.listen(port, () => {
    console.log("http server run success");
  });

  let listenIp = 'http://' + getLocalIPAddress() + ':499';
  console.log("已监听IP: " + listenIp);


});

ipcMain.on("getListenIp", () => {
  let listenIp = 'http://' + getLocalIPAddress() + ':499';
  win.webContents.send("getListenIpSuccess", listenIp);
})


//写入缓存
ipcMain.on("setCache", (event, data) => {
  try {
    // console.log("data 缓存值===>", data);
    // 拼接目标文件的完整路径
    const startPath = path.join(app.getPath('userData'), data.key);
    const baseContent = data.value;
    fs.writeFile(startPath, baseContent, (err) => {
      if (err) {
        win.webContents.send(data.funId, false);
        return;
      }
      win.webContents.send(data.funId, true);
    });
  } catch (error) {
    win.webContents.send(data.funId, false);
  }

});

/**
 * 得到缓存
 */
ipcMain.on("getCache", (event, data) => {
  try {
    // 拼接目标文件的完整路径
    const firstPath = path.join(app.getPath('userData'), data.key);
    //读取文件
    fs.readFile(firstPath, (err, res) => {
      if (err) {
        // res.end(JSON.stringify({ code: 500, message: "文件读取失败" }));
        console.log(" file  read  failed");
        win.webContents.send(data.funId, '');
        return;
      }
      // 将二进制数据转换为字符串，使用 'utf8' 编码格式
      const fileContent = res.toString('utf8');
      win.webContents.send(data.funId, fileContent);
    })
  } catch (error) {
    win.webContents.send(data.funId, '');
  }
});


function getLocalIPAddress() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      // 检查IPv4非内部地址，且以"192.168"开头
      if (iface.family === 'IPv4' && !iface.internal && iface.address.startsWith('192.168')) {
        return iface.address;
      }
    }
  }
  return '127.0.0.1'; // 如果没有找到符合条件的地址，返回localhost
}



globalThis.__filename = fileURLToPath(import.meta.url)
globalThis.__dirname = dirname(__filename)

// The built directory structure
//
// ├─┬ dist-electron
// │ ├─┬ main
// │ │ └── index.js    > Electron-Main
// │ └─┬ preload
// │   └── index.mjs    > Preload-Scripts
// ├─┬ dist
// │ └── index.html    > Electron-Renderer
//
process.env.DIST_ELECTRON = join(__dirname, '..')
process.env.DIST = join(process.env.DIST_ELECTRON, '../dist')
process.env.VITE_PUBLIC = process.env.VITE_DEV_SERVER_URL
  ? join(process.env.DIST_ELECTRON, '../public')
  : process.env.DIST

// Disable GPU Acceleration for Windows 7
if (release().startsWith('6.1')) app.disableHardwareAcceleration()

// Set application name for Windows 10+ notifications
if (process.platform === 'win32') app.setAppUserModelId(app.getName())

if (!app.requestSingleInstanceLock()) {
  app.quit()
  process.exit(0)
}

// Remove electron security warnings
// This warning only shows in development mode
// Read more on https://www.electronjs.org/docs/latest/tutorial/security
// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

let win: BrowserWindow | null = null
// Here, you can also use other preload
const preload = join(__dirname, '../preload/index.mjs')
const url = process.env.VITE_DEV_SERVER_URL
const indexHtml = join(process.env.DIST, 'index.html')


async function createWindow() {
  win = new BrowserWindow({
    title: 'Main window',
    icon: join(process.env.VITE_PUBLIC, 'logo.png'),
    webPreferences: {
      preload,
      webviewTag: true,
      nodeIntegration: true,// 允许渲染进程使用 Node.js API
      webSecurity: false,
      // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production
      // nodeIntegration: true,

      // Consider using contextBridge.exposeInMainWorld
      // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation
      // contextIsolation: false,
    },
  })

  // 创建一个空的菜单，并将其设置为窗口的菜单(关闭electron的默认菜单栏)
  const menu = Menu.buildFromTemplate([]);
  Menu.setApplicationMenu(menu);


  // 进入全屏模式
  win.maximize();

  if (process.env.VITE_DEV_SERVER_URL) { // electron-vite-vue#298
    win.loadURL(url)
    // Open devTool if the app is not packaged
    win.webContents.openDevTools()
  } else {
    win.loadFile(indexHtml)
  }

  // Test actively push message to the Electron-Renderer
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', new Date().toLocaleString())
  })

  // Make all links open with the browser, not with the application
  win.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith('https:')) shell.openExternal(url)
    return { action: 'deny' }
  })
  // win.webContents.on('will-navigate', (event, url) => { }) #344


}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  win = null
  if (process.platform !== 'darwin') app.quit()
})

app.on('second-instance', () => {
  if (win) {
    // Focus on the main window if the user tried to open another
    if (win.isMinimized()) win.restore()
    win.focus()
  }
})

app.on('activate', () => {
  const allWindows = BrowserWindow.getAllWindows()
  if (allWindows.length) {
    allWindows[0].focus()
  } else {
    createWindow()
  }
})

// New window example arg: new windows url
ipcMain.handle('open-win', (_, arg) => {
  const childWindow = new BrowserWindow({
    webPreferences: {
      preload,
      nodeIntegration: true,
      contextIsolation: false,
    },
  })

  if (process.env.VITE_DEV_SERVER_URL) {
    childWindow.loadURL(`${url}#${arg}`)
  } else {
    childWindow.loadFile(indexHtml, { hash: arg })
  }
})












/**
 * 生成指定长度的随机字符
 */
function rand(len: number) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < len; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }
  return result;
}


